package su.product.module;

/**
 * 产品管理
 */
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.kuakao.core.dto.PagerDTO;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import su.product.entity.Cate;
import su.product.entity.Product;
import su.product.entity.ProductPrice;
import su.product.service.CateService;
import su.product.service.MaterialService;
import su.product.service.ProductService;
import su.tool.RegexUtil;
import su.tool.SuDateUtils;
import su.tool.SuDoubleUtils;
import su.tool.SuIntUtils;
@Controller
@RequestMapping("/admin/product")
public class ProductServlet {

	@Autowired
	private CateService cateService;
	
	@Autowired
	private ProductService productService;

	@Autowired
	private MaterialService materialService;

	protected final Log log = LogFactory.getLog(getClass());
	/**
	 * 首页
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("product_index")
	public String productIndex(HttpServletRequest request, Model model){
		return "/maintain/product/product_index";
	}
	/**
	 * 分类下的产品列表
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("getProductsByCate")
	public String getProductsByCate(HttpServletRequest request,PagerDTO s, Model model){
		
		String cateIdStr = request.getParameter("cateId");
		if(StringUtils.isBlank(cateIdStr)){
			model.addAttribute("errorCode", "要查看产品列表，请先选择一个分类");
			return "su_error";
		}
		s.setS3(cateIdStr);
		List<Product> list = productService.getProductsByCate(s);
		model.addAttribute("list", list);
		model.addAttribute("_page", s);
		model.addAttribute("cateid", cateIdStr);
		
		return "/maintain/product/product_list";
	}
	/**
	 * 产品详情
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("product_detail")
	public String productDetail(HttpServletRequest request, Model model) {
        int id = SuIntUtils.getInt(request.getParameter("id"));
        if(id==0){
        	model.addAttribute("errorCode", "请选择产品");
        	return "su_error";
        }
        //基本信息
        Product product = productService.getProductById(id);
        model.addAttribute("baseinfo", product);
        //所属分类
        Cate cate = cateService.getById(product.getCateid());
        model.addAttribute("cateInfo", cate);
        //价格信息
        List<ProductPrice> prices = productService.getPriceByProductId(id);
        model.addAttribute("priceInfos", prices);
		return "/maintain/product/product_detail";
	}
	/**
	 * 到 添加/编辑 产品信息页面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("to_edit_product")
	public String toEditProduct(HttpServletRequest request, Model model) {
        int id = SuIntUtils.getInt(request.getParameter("id"));
        if(id>0){
        	Product product = productService.getProductById(id);
            model.addAttribute("baseinfo", product);
        }
        model.addAttribute("cateid", request.getParameter("cateid"));
		return "/maintain/product/product_edit";
	}

	/**
	 * 添加一个产品
	 * @param request
	 * @param response
	 * @param cate
	 * @param model
	 */
	@RequestMapping("do_save_product")
	public String doSaveProduct(HttpServletRequest request,HttpServletResponse response,Product product, Model model){
		String res = "";
		try {
			productService.saveProduct(product);
		} catch (Exception e) {
			log.error(e.getMessage());
			res = e.getMessage();
		}
		if(StringUtils.isNotBlank(res)){
			request.setAttribute("errorCode", res);
			return "su_error";
		}
		return "redirect:/admin/product/getProductsByCate.action?cateId="+product.getCateid();
	}
	/**
	 * 删除
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping("do_remove")
	public void doRemove(HttpServletRequest request,HttpServletResponse response, Model model){
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
        PrintWriter writer = null;
		try {
			writer = response.getWriter();
		} catch (IOException e) {
			log.error(e.getMessage());
		}
		if(writer==null)return;
		Map<String,String> msgs = new HashMap<String,String>();
		
		int id = SuIntUtils.getInt(request.getParameter("id"));
		
		if(id==0){
			msgs.put("no id", "请选择要删除的数据");
		}else{
			String msg = "";
			try {
				productService.removeProduct(id);
			} catch (Exception e) {
				log.error(e.getMessage());
				msg = e.getMessage();
			}
			
			if(StringUtils.isNotBlank(msg)){
				msgs.put("service error", msg);
			}else{
				msgs.put("success", "success");
			}
		}
		
		writer.print(JSONObject.fromObject(msgs));
		writer.flush();
		writer.close();
    }
	/**
	 * 根据id或简拼得到产品列表
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping("search_product")
	public void searchProduct(HttpServletRequest request,HttpServletResponse response, Model model){
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
        PrintWriter writer = null;
		try {
			writer = response.getWriter();
		} catch (IOException e) {
			log.error(e.getMessage());
		}
		if(writer == null)return;
		
		String q = request.getParameter("term");
		if(StringUtils.isBlank(q) || q.length()>6){//查询条件为空或字符数大于6(显示的汉字)时不予查询
			writer.print("");
			writer.flush();
			writer.close();
			return;
		}
		//System.out.println("aa==="+q);
		List list = new ArrayList();
		Map<String ,Object> map;
		PagerDTO dto = new PagerDTO();
		//
		if(RegexUtil.isNumeric(q)){//id
			dto.setS1(q);
		}else{//简拼
			dto.setS2(q);
		}
		List<Product> productList = productService.getProductsByCate(dto);
		if(productList!=null && !productList.isEmpty()){
			for(Product product : productList){
				map=new HashMap<String, Object>();
				map.put("id", product.getId());
				map.put("label", product.getPname());
				list.add(map);
			}
		}

		writer.print(JSONArray.fromObject(list.toArray()).toString());
		writer.flush();
		writer.close();
    }
	//==============产品价格信息管理
	/**
	 * 取产品的价格信息
	 */
	@RequestMapping("get_product_prices")
	public String getProductPrices(HttpServletRequest request, Model model){
		String productIdStr = request.getParameter("productId");
		if(StringUtils.isBlank(productIdStr)){
			model.addAttribute("errorCode", "请选择一个产品");
			return "/su_error";
		}
		List<ProductPrice> list = productService.getPriceByProductId(Integer.parseInt(productIdStr));
		model.addAttribute("list", list);
		
		model.addAttribute("productId", productIdStr);
		return "/maintain/product/product_price_list";
	}
	/**
	 * 添加/修改 产品价格信息
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("to_edit_product_price")
	public String toEditProductPrice(HttpServletRequest request, Model model) {
        int id = SuIntUtils.getInt(request.getParameter("id"));
        if(id>0){
        	ProductPrice baseinfo = productService.getProductPriceById(id);
            model.addAttribute("baseinfo", baseinfo);
        }
        model.addAttribute("pid", request.getParameter("pid"));
		return "/maintain/product/product_price_edit";
	}
	/**
	 * 保存 产品价格信息
	 * @param request
	 * @param response
	 * @param o
	 * @param model
	 * @return
	 */
	@RequestMapping("do_save_product_price")
	public String doSaveProductPrice(HttpServletRequest request,HttpServletResponse response,ProductPrice o, Model model){
		String res = "";
		o.setTimefrom(SuDateUtils.getDateByFormatString(o.getTimefromStr(),"yyyy-MM-dd"));
		o.setTimeto(SuDateUtils.getDateByFormatString(o.getTimetoStr(),"yyyy-MM-dd"));
		try {
			productService.saveProductPrice(o);
		} catch (Exception e) {
			log.error(e.getMessage());
			res = e.getMessage();
		}
		if(StringUtils.isNotBlank(res)){
			request.setAttribute("errorCode", res);
			return "su_error";
		}
		return "redirect:/admin/product/get_product_prices.action?productId="+o.getPid();
	}
	/**
	 * 删除
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping("do_remove_product_price")
	public void doRemoveProductPrice(HttpServletRequest request,HttpServletResponse response, Model model){
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
        PrintWriter writer = null;
		try {
			writer = response.getWriter();
		} catch (IOException e) {
			log.error(e.getMessage());
		}
		if(writer==null)return;
		Map<String,String> msgs = new HashMap<String,String>();
		
		int id = SuIntUtils.getInt(request.getParameter("id"));
		
		if(id==0){
			msgs.put("no id", "请选择要删除的数据");
		}else{
			String msg = "";
			try {
				productService.removeProductPrice(id);
			} catch (Exception e) {
				log.error(e.getMessage());
				msg = e.getMessage();
			}
			
			if(StringUtils.isNotBlank(msg)){
				msgs.put("service error", msg);
			}else{
				msgs.put("success", "success");
			}
		}
		
		writer.print(JSONObject.fromObject(msgs));
		writer.flush();
		writer.close();
    }
	/**
	 * 到 价格浮动 页面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("to_change_price")
	public String toChangePrice(HttpServletRequest request, Model model) {
		model.addAttribute("productId", request.getParameter("productId"));
        model.addAttribute("cateId", request.getParameter("cateId"));
		return "/maintain/product/product_change_price";
	}
	/**
	 * 产品价格浮动
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("do_change_all_price")
	public String doChangeAllPrice(HttpServletRequest request,HttpServletResponse response, Model model){
		String cateId = request.getParameter("cateId");
		if(StringUtils.isBlank(cateId)){
			request.setAttribute("errorCode", "请选择产品分类");
			return "su_error";
		}
		String productIdStr = request.getParameter("productId");
		if(StringUtils.isBlank(productIdStr)){
			request.setAttribute("errorCode", "请选择要修改的产品");
			return "su_error";
		}
		String dateStr = request.getParameter("dateStr");
		if(StringUtils.isBlank(dateStr)){
			request.setAttribute("errorCode", "请选择价格浮动开始的日期");
			return "su_error";
		}
		String priceStr = request.getParameter("price");
		if(StringUtils.isBlank(priceStr)){
			request.setAttribute("errorCode", "请输入价格浮动金额");
			return "su_error";
		}
		String res = "";
		try {
			productService.updateAllPrice(Integer.parseInt(productIdStr), dateStr, SuDoubleUtils.getDoubleFromObj(priceStr));
		} catch (Exception e) {
			log.error(e.getMessage());
			res = e.getMessage();
		}
		if(StringUtils.isNotBlank(res)){
			request.setAttribute("errorCode", res);
			return "su_error";
		}
		return "redirect:/admin/product/getProductsByCate.action?cateId="+cateId;
	}
	
	/**
	 * 修改产品的分类
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("do_update_cate")
	public String doUpdateCate(HttpServletRequest request,HttpServletResponse response, Model model){
		String productId = request.getParameter("productId");
		String oldCateId = request.getParameter("oldCateId");
		String newCateId = request.getParameter("newCateId");
		String productType = request.getParameter("productType");
		if(StringUtils.isBlank(productId)){
			request.setAttribute("errorCode", "请选择要修改分类的产品");
			return "su_error";
		}
		if(StringUtils.isBlank(oldCateId)){
			request.setAttribute("errorCode", "修改分类操作异常，请刷新页面，重新操作");
			return "su_error";
		}
		if(StringUtils.isBlank(newCateId)){
			request.setAttribute("errorCode", "请输入您想要修改到的分类的id");
			return "su_error";
		}
		if(StringUtils.isBlank(productType)){
			request.setAttribute("errorCode", "请选择您想要修改分类的是产品还是原料");
			return "su_error";
		}
		String res = "";
		try {
			if("1".equals(productType))productService.updateProductCate(Integer.parseInt(productId),Integer.parseInt(oldCateId), Integer.parseInt(newCateId));
			if("2".equals(productType))materialService.updateMaterialCate(Integer.parseInt(productId),Integer.parseInt(oldCateId), Integer.parseInt(newCateId));
		} catch (Exception e) {
			log.error(e.getMessage());
			res = e.getMessage();
		}
		if(StringUtils.isNotBlank(res)){
			request.setAttribute("errorCode", res);
			return "su_error";
		}
		if("1".equals(productType))return "redirect:/admin/product/getProductsByCate.action?cateId="+oldCateId;
		else return "redirect:/admin/material/getMaterialsByCate.action?cateId="+oldCateId;
	}
}
